package controllers

import (
	"github.com/dchest/captcha"
	"log"
	"micro-bbs/initialize"
	"micro-bbs/libs"
	"micro-bbs/services"
	"github.com/gin-gonic/gin"
	"net/http"
	"errors"
)

type CaptchaController struct {

	CaptchaService services.CaptchaInterfaceService
}

func NewCaptchaController() *CaptchaController {
	obj := &CaptchaController{
		CaptchaService: services.NewCaptchaService(),
	}
	return obj
}


//获得验证码 ID
func (this *CaptchaController) Generate(c *gin.Context){
	id := captcha.NewLen(4)
	if id == "" {
		log.Println("generate captcha error", errors.New("验证码ID创建失败"))
	}
	c.JSON(http.StatusOK, libs.ReturnJson(200,"", gin.H{
		"id": id,
	}))
}

//获取验证码图片
func (this *CaptchaController) GetImage(c *gin.Context){
	id := c.Param("id")
	if id == "" {
		http.Error(c.Writer, "Bad Request", http.StatusBadRequest)
		return
	}
	c.Writer.Header().Set("Content-Type", "image/png")
	if err := captcha.WriteImage(c.Writer, id, 120, 80); err != nil {
		log.Println("show captcha error", err)
	}
}

//效验验证码
func (this *CaptchaController) Verify (c *gin.Context){
	id := c.Param("id")
	value := c.Param("value")
	if id == "" || value == "" {
		initialize.IrisLog.Infof("[效验验证码传参错误]-[id:%s]-[value:%s]", id, value)
	}
	verifyVal := this.CaptchaService.VerifyCaptcha(id, value)
	if verifyVal {
		c.JSON(http.StatusOK, libs.ReturnJson(200,"", gin.H{
			"check": true,
		}))
	}else{
		c.JSON(http.StatusOK, libs.ReturnJson(200,"", gin.H{
			"check": false,
		}))
	}
}
